import React, { useState, useRef } from 'react';
import { connect, FormattedMessage, useIntl } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Table, Button, Tabs, Card, message, Modal, Tag } from 'antd';
import { EmpSelectCmp } from '@/components/FormItemSelect';
import request from '@/utils/request';
import PrintModal from '@/components/PrintModal';
import TempleteIssue from '../PrintTemplete/TempleteIssue';
import QuickMenu from '@/components/QuickMenu';
import OperpQuery from '@/components/OperpQuery';

const apiURL = '/api/services/app/JobMtl/';
const { TabPane } = Tabs;

type EditableTableProps = Parameters<typeof Table>[0];
type DataType = {
  key: React.Key;
  jobComplete: boolean;
  issuedComplete: boolean;
  jobNum: string;
  assemblySeq: number;
  mtlSeq: number;
  partNum: string;
  partDescription: string;
  qtyPer: number;
  requiredQty: number;
  fixedQty: boolean;
  ium: string;
  relatedOperation: number;
  relatedOpRev: string;
  issuedQty: number;
  unIssuedQty: number;
  reqDate: string;
  warehouseCode: string;
  binNum: string;
  id: string;
  pickQty: number;
  pickUser: string;
  pickedQty: number;
  allowPickQty: number;
};

const MfgMtl: React.FC<any> = (props) => {
  const [selectedKeys, setSelectedKeys] = useState<any[]>([]);
  const [selectedRows, setSelectedRows] = useState<any[]>([]);
  const [visible, setVisible] = useState<boolean>(false);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [selectedEmp, setSelectedEmp] = useState<string>('');
  const [printData, setPrintData] = useState<any[]>([]);
  const [freshNum, setFreshNum] = useState<number>(0);
  const [visible2, setVisible2] = useState<boolean>(false);
  const [PickNum, setPickNum] = useState<string>('');
  const [actTab, setActTab] = useState<string>('1');

  const intl = useIntl();
  const printArea = useRef<any>();

  const switchVisible = (visible = false) => {
    if (selectedRows.length <= 0) {
      message.error(intl.formatMessage({ id: 'pages.select.material' }));
    } else {
      setVisible(visible);
    }
  };

  const handleRowSelect = (selectedKeys: any, selectedRows: any) => {
    setSelectedKeys(selectedKeys);
    setSelectedRows(selectedRows);
  };

  const handleSubmit = async () => {
    if (selectedRows.length <= 0) {
      return message.warning(intl.formatMessage({ id: 'pages.select.pickOrder' }));
    }
    if (!selectedEmp) {
      return message.warning(intl.formatMessage({ id: 'pages.select.picker' }));
    }

    let isok: boolean = true;
    selectedRows.forEach((item: DataType) => {
      item.pickUser = selectedEmp;
      if (item.pickQty > item.allowPickQty) {
        message.warning(intl.formatMessage({ id: 'pages.pickQty.exceed' }));
        isok = false;
      }
      if (item.pickQty <= 0) {
        message.warning(intl.formatMessage({ id: 'pages.pickQty.zero' }));
        isok = false;
      }
    });

    if (isok) {
      setLoading(true);
      const resp = await request(apiURL + 'AppIssueMtl', {
        method: 'POST',
        data: selectedRows,
      });
      if (resp && resp.success) {
        message.success(intl.formatMessage({ id: 'pages.pick.success' }));
        setPickNum(resp.result);
        setLoading(false);
        setFreshNum(freshNum + 1);
      }
      setPrintData(selectedRows);
      switchVisible();
    }
  };

  const selectEmp = (values: any) => {
    setSelectedEmp(values);
  };

  const doPrint = () => {
    setVisible2(true);
  };

  const quickFill = () => {
    const newDataSource = dataSource.map((item: any) => {
      const selectedItem = selectedRows.find((row: any) => row.RowId === item.RowId);
      if (selectedItem) {
        return {
          ...item,
          pickQty: item.allowPickQty,
        };
      }
      return item;
    });
    setDataSource(newDataSource);
  };

  const delAppMtl = () => {
    const ids: any = [];
    printData.forEach((item: any) => {
      ids.push(item.id);
    });
    setLoading(true);
    request(apiURL + 'DelAppMtl', {
      method: 'POST',
      data: ids,
    }).then(() => {
      setFreshNum(freshNum + 1);
      setLoading(false);
    });
  };

  const doComplete = () => {
    const ids: any = [];
    printData.forEach((item: any) => {
      ids.push(item.id);
    });
    setLoading(true);
    request(apiURL + 'BatchComplete', {
      method: 'POST',
      data: ids,
    }).then(() => {
      setFreshNum(freshNum + 1);
      setLoading(false);
    });
  };

  const checkQty = (rule: any, value: any, callback: any) => {
    // const editSelectRow: never[] = [];
    // if (value) {
    //   if (editSelectRow.allowPickQty < value || value <= 0) {
    //     callback(
    //       <FormattedMessage id="value must be greater than 0 and less than onhand quantity" />,
    //     );
    //   } else {
    //     callback();
    //   }
    // } else {
    //   callback(<FormattedMessage id="inspQty.required" />);
    // }
  };

  const handleRowSave = async (rowKey: any, data: any, row: any) => {
    const newDataSource = dataSource.map((element: any) => {
      if (rowKey === element.RowId) {
        return {
          ...element,
          pickQty: data.pickQty > row.allowPickQty ? row.allowPickQty : data.pickQty,
        };
      }
      return element;
    });
    setDataSource(newDataSource);
  };

  const rowSelection = {
    selectedRowKeys: selectedKeys,
    onChange: handleRowSelect,
    preserveSelectedRowKeys: false,
  };

  const rowSelection2 = {
    onChange: (_selectedKeys: any, selectedRows: any) => {
      setPrintData(selectedRows);
    },
  };

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Card>
        <Tabs defaultActiveKey="1" onChange={(e) => setActTab(e)}>
          <TabPane tab={<FormattedMessage id="pages.pick" />} key="1">
            <OperpQuery
              rowKey="RowId"
              rowSelection={rowSelection}
              sysReportName="AllowPicMtl"
              scroll={{ x: 'max-content', y: '600px' }}
              freshNum={freshNum}
              editable={true}
              dataSource={dataSource}
              onload={(data: any) => setDataSource(data)}
              onRowSave={handleRowSave}
              optionText={intl.formatMessage({ id: 'pages.pick' })}
              toolBarRender={[
                <Tag color="processing">
                  <FormattedMessage id="pages.pickNum" />：{PickNum}
                </Tag>,
                <EmpSelectCmp
                  width={120}
                  placeholder={intl.formatMessage({ id: 'pages.select.picker' })}
                  onChange={selectEmp}
                  showSearch
                />,
                <Button type="primary" onClick={handleSubmit} loading={loading}>
                  <FormattedMessage id="pages.apply.pick" />
                </Button>,
                <Button type="primary" onClick={quickFill}>
                  <FormattedMessage id="pages.quick.fill" />
                </Button>,
                <QuickMenu path="/manufacture/mfgMtl" icon="icon-survey" title="pages.PickMtl" />,
              ]}
            />
          </TabPane>
          <TabPane tab={<FormattedMessage id="pages.pick.record" />} key="2">
            <OperpQuery
              rowKey='RowId'
              rowSelection={rowSelection2}
              sysReportName="ReportIssueMtl"
              scroll={{ x: 'max-content', y: '600px' }}
              freshNum={freshNum}
              toolBarRender={[
                <Button type="primary" onClick={doPrint} key="B1">
                  <FormattedMessage id="pages.print" />
                </Button>,
                <Button type="primary" danger onClick={delAppMtl} key="B2" loading={loading}>
                  <FormattedMessage id="pages.revoke" />
                </Button>,
                <Button type="default" onClick={doComplete}>
                  <FormattedMessage id="pages.complete" />
                </Button>,
              ]}
            />
          </TabPane>
        </Tabs>
      </Card>
      <div ref={printArea} hidden>
        <TempleteIssue
          data={printData}
          ref={printArea}
          hidden
        />
      </div>
      <Modal
        width={1024}
        title={intl.formatMessage({ id: 'pages.pick.print' })}
        visible={visible2}
        destroyOnClose={true}
        onCancel={() => setVisible2(false)}
        footer={false}
      >
        <PrintModal>
          <TempleteIssue data={printData} configData={props.currentConfig} />
        </PrintModal>
      </Modal>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp, user }: API.IConnectState) => ({
  response: Abp.response,
  currentConfig: user.currentConfig,
}))(MfgMtl);
